<template>
  <div class="map-container">
    <div class="map-header">
      <div class="map-header-left">
        <el-button size="small" type="plain" @click="handleMovingTarget"
          >加载动目标</el-button
        >
        <el-button size="small" type="plain" @click="handleBoomParticle"
          >添加爆炸</el-button
        >
        <el-button size="small" type="plain" @click="handleUnlock"
          >解锁视角</el-button
        >
        <el-button size="small" type="plain" @click="handleCamberRadar"
          >绘制扇形</el-button
        >
        <el-button size="small" type="plain" @click="handleDrawDragDiv"
          >拖拽标牌</el-button
        >
        <el-button size="small" type="plain" @click="handleTestRadar"
          >球状雷达</el-button
        >
        <el-button size="small" type="plain" @click="handleTestEllipse"
          >加载Ellipse</el-button
        >
        <el-button size="small" type="plain" @click="testRootState"
          >testRootState</el-button
        >
      </div>
      <div class="map-header-right">仿真时间 00:00:00</div>
    </div>
    <ul class="side-menu">
      <el-tooltip
        v-for="(item, index) in menuList"
        :key="index"
        class="item"
        effect="dark"
        :content="item.name"
        placement="left"
      >
        <li :class="['iconfont', item.icon]" @click="handleOpenMenu(item)"></li>
      </el-tooltip>
    </ul>
    <div class="simulation-control"></div>
    <div class="map-content" id="mapContainer"></div>
    <VisibleControl ref="visibleControlRef" @menuClose="menuClose" />
    <LayerManage v-if="flag" ref="layerManageRef" @menuClose="menuClose" />
    <MapMeasure ref="mapMeasureRef" @menuClose="menuClose" />
    <PlotPanel ref="plotPanelRef" @menuClose="menuClose" />
    <EntityManage ref="entityManageRef" @menuClose="menuClose" />
    <EntityRightMenu ref="entityRightMenuRef" @menuClose="menuClose" />
    <Chart ref="chartRef" @menuClose="menuClose" />
  </div>
</template>

<script>
// 显隐控制组件
import VisibleControl from "@/views/map3d/modules/visibleControl";
// 图层管理
import LayerManage from "@/views/map3d/modules/layerManage";
// 地图量算
import MapMeasure from "@/views/map3d/modules/mapMeasure";
// 标绘面板
import PlotPanel from "@/views/map3d/modules/plotPanel";
// 实体管理
import EntityManage from "@/views/map3d/modules/entityManage";
// 实体右键菜单
import EntityRightMenu from "@/views/map3d/modules/entityRightMenu";
// 图表
import Chart from "@/views/map3d/modules/chart";
// 解析gif 爆炸
import SuperGif from "@/views/map3d/modules/utils/libgif.js";
import DrawFanShape from "@/views/map3d/modules/utils/DrawFanShape.js";
// 引入可拖拽标牌类
import DragDiv from "@/views/map3d/modules/utils/dragDiv.js";
export default {
  name: "Map3d",
  data() {
    return {
      menuList: [
        {
          icon: "icon-cengshu",
          show: false,
          name: "图层管理",
          com: "layerManageRef",
        },
        {
          icon: "icon-tushangcehui",
          show: false,
          name: "地图标绘",
          com: "plotPanelRef",
        },
        {
          icon: "icon-zuichu",
          show: false,
          name: "实体管理",
          com: "entityManageRef",
        },
        {
          icon: "icon-zuichu",
          show: false,
          name: "显隐控制",
          com: "visibleControlRef",
        },
        {
          icon: "icon-tushangliangsuan",
          show: false,
          name: "地图量算",
          com: "mapMeasureRef",
        },
        {
          icon: "icon-tushangliangsuan",
          show: false,
          name: "图表",
          com: "chartRef",
        },
      ],
      flag: false,
    };
  },
  components: {
    VisibleControl,
    LayerManage,
    MapMeasure,
    PlotPanel,
    EntityManage,
    EntityRightMenu,
    Chart,
  },
  mounted() {
    this.initMap();
  },
  methods: {
    handleOpenMenu(item) {
      if (!item.show) {
        this.$refs[item.com].open();
        item.show = true;
      } else {
        this.$refs[item.com].handleClose();
      }
    },
    menuClose(comName) {
      let findObj = this.menuList.find((item) => item.com === comName);
      findObj.show = false;
    },
    initMap() {
      window.viewer = new Cesium.Viewer("mapContainer", {
        imageryProvider: new Cesium.TileMapServiceImageryProvider({
          url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
        }),
        animation: true, // 设置动画小组件关闭展示
        timeline: true, // 时间轴关闭展示
        infoBox: false, // 信息盒子关闭展示
        geocoder: false, // 地理编码搜索关闭展示
        baseLayerPicker: false, // 基础图层选择器关闭展示
        sceneModePicker: false, // 场景选择器关闭展示
        fullscreenButton: false, // 全屏按钮关闭展示
        navigationInstructionsInitiallyVisible: false, // 导航说明是否最初展示
        navigationHelpButton: false, // 导航帮助按钮关闭展示
        homeButton: false,
        shouldAnimate: true,
      });

      // 设置中国视角参数
      const chinaView = {
        destination: Cesium.Cartesian3.fromDegrees(104, 28, 8000000),
        orientation: {
          heading: 0,
          pitch: -Cesium.Math.PI_OVER_TWO,
          roll: 0,
        },
      };

      // 设置初始视角
      window.viewer.camera.setView(chinaView);

      this.flag = true;
      document.getElementsByClassName("cesium-viewer-bottom")[0].style.display =
        "none";
      window.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      // 罗盘，指北针
      let compassTool = new vis3d.common.Navigation(window.viewer, {
        enableCompass: true, // 罗盘
        /* compass: { // 罗盘位置设置
        style: {
            top: "120px",
            left: "120px"
        }
    }, */
        enableZoomControls: true, // 缩放控制器
        enableDistanceLegend: true, // 比例尺
        /*  distanceLegend: { // 比例尺位置
            style: {
                top: "120px",
                left: "120px"
            }
        }, */
        enableCompassOuterRing: true, // 罗盘外环
        view: {
          x: 104,
          y: 28,
          z: 8000000,
          heading: 0,
          pitch: -90,
          roll: 0,
          duration: 2,
        }, // 初始化视角
      });
      // 经纬度信息
      let LnglatTool = new vis3d.common.LnglatTool(window.viewer, {});
      //实体的右键菜单
      let handler = new Cesium.ScreenSpaceEventHandler(
        window.viewer.scene.canvas
      );
      // 右键事件
      this.EventListener_MouseRightClick(handler);
      window.viewer.scene.globe.depthTestAgainstTerrain = false;
    },
    EventListener_MouseRightClick(handler) {
      let that = this;
      handler.setInputAction(function (evt) {
        //设置监听方法
        let scene = viewer.scene;
        let pick = scene.pick(evt.position);
        if (pick == undefined) {
        } else {
          let entity = window.viewer.entities.getById(pick.id.id);
          if (entity.customName == "动态实体") {
            let data = {
              name: entity.name,
              side: entity.side,
            };
            that.$refs.entityRightMenuRef.open(data);
          }
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    // 添加动目标
    handleMovingTarget() {
      let start = Cesium.JulianDate.fromDate(new Date()); // 开始时间加8小时改为北京时间
      let stop = Cesium.JulianDate.addSeconds(
        start,
        400,
        new Cesium.JulianDate()
      ); // 设置结束时间为开始时间加400秒
      // 设置时钟开始时间
      window.viewer.clock.startTime = start.clone();
      // 设置时钟当前时间
      window.viewer.clock.currentTime = start.clone();
      // 设置时钟结束时间
      window.viewer.clock.stopTime = stop.clone();
      // 时间速率，数字越大时间过的越快，
      window.viewer.clock.multiplier = 1;
      let obj = {
        longitude: 120.998994,
        dimension: 32.66277,
        height: 0,
        time: 0,
      };
      let blueObj = {
        longitude: 123.99899399999983,
        dimension: 35.662770000000044,
        height: 0,
        time: 0,
      };
      let blueProperty = new Cesium.SampledPositionProperty();
      // 在最终位置显示实体
      blueProperty.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD; // 关键！
      blueProperty.backwardExtrapolationType = Cesium.ExtrapolationType.HOLD;
      let property = new Cesium.SampledPositionProperty();
      let interval = setInterval(() => {
        obj.longitude += 0.1;
        obj.dimension += 0.1;
        obj.height += 5000;
        obj.time += 1;
        let cobyobj = JSON.parse(JSON.stringify(obj));
        let time = Cesium.JulianDate.addSeconds(
          Cesium.JulianDate.fromDate(new Date()),
          cobyobj.time,
          new Cesium.JulianDate()
        );
        let position = Cesium.Cartesian3.fromDegrees(
          cobyobj.longitude,
          cobyobj.dimension,
          cobyobj.height
        );
        // 添加位置，和时间对应
        property.addSample(time, position);
        // 蓝方
        blueObj.longitude -= 0.1;
        blueObj.dimension -= 0.1;
        blueObj.time += 1;
        let cobyBlueObj = JSON.parse(JSON.stringify(blueObj));
        let blueTime = Cesium.JulianDate.addSeconds(
          Cesium.JulianDate.fromDate(new Date()),
          cobyBlueObj.time,
          new Cesium.JulianDate()
        );
        let bluePosition = Cesium.Cartesian3.fromDegrees(
          cobyBlueObj.longitude,
          cobyBlueObj.dimension,
          cobyBlueObj.height
        );
        // 添加位置，和时间对应
        blueProperty.addSample(blueTime, bluePosition);
        if (obj.time > 10) {
          clearInterval(interval);

          // 获取最后一个有效时间的朝向值
          // const finalOrientation = entity.orientation.getValue(
          //   Cesium.JulianDate.now()
          // );

          // // 覆盖为固定朝向属性
          // entity.orientation = new Cesium.ConstantProperty(finalOrientation);
        }
      }, 1000);
      // 初始化实体信息
      let time = Cesium.JulianDate.addSeconds(
        Cesium.JulianDate.fromDate(new Date()),
        obj.time,
        new Cesium.JulianDate()
      );
      let position = Cesium.Cartesian3.fromDegrees(
        obj.longitude,
        obj.dimension,
        obj.height
      );
      let F22Entity = this.createModel(
        {
          name: "F22",
          moduleUrl: "./glb/zhanji.glb",
          symblUrl: "./symbol/plane.png",
          side: 1,
          sideColr: Cesium.Color.RED,
        },
        start,
        stop
      );
      F22Entity.position.addSample(time, position);
      let testInterval = setInterval(() => {
        obj.longitude += 0.1;
        obj.dimension += 0.1;
        obj.time += 1;
        let time = Cesium.JulianDate.addSeconds(
          Cesium.JulianDate.fromDate(new Date()),
          obj.time,
          new Cesium.JulianDate()
        );
        let position = Cesium.Cartesian3.fromDegrees(
          obj.longitude,
          obj.dimension,
          obj.height
        );
        // 添加位置，和时间对应
        F22Entity.position.addSample(time, position);
      });
      let missileEntity = this.createModel(
        {
          name: "导弹",
          moduleUrl: "./glb/missile.glb",
          symblUrl: "./symbol/missle.png",
          side: 2,
          sideColr: Cesium.Color.BLUE,
        },
        start,
        stop
      );
    },
    // 添加模型
    createModel(option, start, stop) {
      // 闪烁参数
      let x = 0.5;
      let flog = true;
      let property = new Cesium.SampledPositionProperty();
      property.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD; // 关键！
      property.backwardExtrapolationType = Cesium.ExtrapolationType.HOLD;
      const entity = viewer.entities.add({
        name: option.name,
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({
            start: start,
            stop: stop,
          }),
        ]),
        position: property,
        orientation: new Cesium.VelocityOrientationProperty(property),
        label: {
          showBackground: true,
          text: option.name,
          font: "12px sans-serif",
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(60, 0), // 像素偏移，使标签不在锚点正上方
          fillColor: option.sideColr,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 10,
          backgroundPadding: new Cesium.Cartesian2(10, 10),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          backgroundColor: Cesium.Color.fromBytes(2, 44, 55, 0.3 * 255),
        },
        // 控制闪烁点，选中状态
        point: {
          show: false, // default
          color: new Cesium.CallbackProperty(function () {
            if (flog) {
              x = x - 0.05;
              if (x <= 0) {
                flog = false;
              }
            } else {
              x = x + 0.05;
              if (x >= 1) {
                flog = true;
              }
            }
            return option.sideColr.withAlpha(x);
          }, false),
          pixelSize: 25, // default: 1
          outlineWidth: 0,
        },
        billboard: {
          image: option.symblUrl,
          color: option.sideColr,
          width: 50,
          height: 50, // 军标高度调整
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            50000000
          ), //单位是米，根据离地距离显示
          alignedAxis: Cesium.Cartesian3.UNIT_Z, // 平行于地面
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          rotation: new Cesium.CallbackProperty(function (time, result) {
            var position = property.getValue(time);
            var velocity = Cesium.Property.getValueOrUndefined(
              property.getVelocityVector,
              time
            );
            console.log("velocity", velocity);
            if (Cesium.defined(velocity)) {
              // 平滑处理：使用前几个时间点的平均方向
              var prevTime1 = Cesium.JulianDate.addSeconds(
                time,
                -0.5,
                new Cesium.JulianDate()
              );
              var prevTime2 = Cesium.JulianDate.addSeconds(
                time,
                -1.0,
                new Cesium.JulianDate()
              );

              var vel1 = Cesium.Property.getValueOrUndefined(
                positionProperty.getVelocityVector,
                prevTime1
              );
              var vel2 = Cesium.Property.getValueOrUndefined(
                positionProperty.getVelocityVector,
                prevTime2
              );

              if (Cesium.defined(vel1) && Cesium.defined(vel2)) {
                // 加权平均
                velocity = Cesium.Cartesian3.add(
                  Cesium.Cartesian3.multiplyByScalar(
                    velocity,
                    0.6,
                    new Cesium.Cartesian3()
                  ),
                  Cesium.Cartesian3.add(
                    Cesium.Cartesian3.multiplyByScalar(
                      vel1,
                      0.3,
                      new Cesium.Cartesian3()
                    ),
                    Cesium.Cartesian3.multiplyByScalar(
                      vel2,
                      0.1,
                      new Cesium.Cartesian3()
                    ),
                    new Cesium.Cartesian3()
                  ),
                  new Cesium.Cartesian3()
                );
              }

              var heading = Math.atan2(velocity.x, velocity.y);

              return -heading;
            }
            return 0;
          }, false),
        },
        // model: {
        //   uri: option.moduleUrl,
        //   minimumPixelSize: 128,
        //   maximumScale: 20000,
        //   distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
        //     0,
        //     500000
        //   ), // 实体显示距离
        // },
        path: {
          leadTime: 0,
          trailTime: 60, //路径持续时间
          width: 1, //路径宽度
          resolution: 10, //路径分辨率
          material: option.sideColr,
        },
      });
      // 根据实体朝向，设置军标朝向rotation 是以弧度为单位的
      // entity.billboard.rotation = new Cesium.CallbackProperty(() => {
      //   let or = entity.orientation.getValue(Cesium.JulianDate.now());
      //   let position = entity.position.getValue(Cesium.JulianDate.now());
      //   // 四元数计算三维旋转矩阵
      //   let mtx3 = Cesium.Matrix3.fromQuaternion(or, new Cesium.Matrix3());

      //   // 四维转换矩阵
      //   let mtx4 = Cesium.Matrix4.fromRotationTranslation(
      //     mtx3,
      //     position,
      //     new Cesium.Matrix4()
      //   );

      //   // 计算HeadingPitchRoll，结果为弧度
      //   let hpr = Cesium.Transforms.fixedFrameToHeadingPitchRoll(
      //     mtx4,
      //     Cesium.Ellipsoid.WGS84,
      //     Cesium.Transforms.eastNorthUpToFixedFrame,
      //     new Cesium.HeadingPitchRoll()
      //   );
      //   return hpr.heading; // 飞机图标随飞行方向旋转
      // }, false);
      entity.side = option.side;
      entity.customName = "动态实体";
      return entity;
    },
    // 粒子特效爆炸
    handleBoomParticle() {
      let ent = window.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(120, 24),
      });
      ent.customName = "粒子特效位置";
      let particleSystem = viewer.scene.primitives.add(
        new Cesium.ParticleSystem({
          image: "./symbol/fire.png",
          imageSize: new Cesium.Cartesian2(20, 20),
          // Particle behavior
          particleLife: 1.0,
          speed: 5.0,
          emissionRate: 5.0,
          startColor: Cesium.Color.YELLOW.withAlpha(0.7),
          endColor: Cesium.Color.RED.withAlpha(0.5),
          startScale: 0.5,
          endScale: 8.0,
          minimumParticleLife: 1.0,
          maximumParticleLife: 8.0,
          minimumSpeed: 1.0,
          maximumSpeed: 2.0,
          imageSize: new Cesium.Cartesian2(10, 10),
          lifetime: 2.0,
          emitter: new Cesium.BoxEmitter(
            new Cesium.Cartesian3(10.0, 10.0, 10.0)
          ),
          modelMatrix: computeModelMatrix(ent, Cesium.JulianDate.now()),
          loop: false,
        })
      );
      // let particleSystem = viewer.scene.primitives.add(
      //   new Cesium.ParticleSystem({
      //     image: "./symbol/fire.png",
      //     imageSize: new Cesium.Cartesian2(10.0, 10.0), //粒子图像尺寸（以像素为单位）的minimumImageSize和maximumImageSize
      //     startColor: Cesium.Color.RED.withAlpha(0.7), //粒子在其生命初期的颜色
      //     endColor: Cesium.Color.YELLOW.withAlpha(0.3), //粒子在其生命结束的颜色
      //     minimumSpeed: 1, //最小速度
      //     maximumSpeed: 2, //最大速度
      //     startScale: 10, //粒子图像的初始比例
      //     endScale: 40, //粒子图像的结束比例
      //     minimumParticleLife: 1, //粒子生命的可能持续时间的最小范围
      //     maximumParticleLife: 6, //粒子生命的可能持续时间的最大范围
      //     emissionRate: 4, //每秒要发射的粒子数
      //     //粒子系统生命周期内，按照指定周期，爆发一定数量的粒子。三个参数（time，minimum，maximum）
      //     bursts: [
      //       // 爆炸出的粒子的密度
      //       new Cesium.ParticleBurst({
      //         time: 5.0,
      //         minimum: 10,
      //         maximum: 100,
      //       }),
      //       new Cesium.ParticleBurst({
      //         time: 10.0,
      //         minimum: 50,
      //         maximum: 100,
      //       }),
      //       new Cesium.ParticleBurst({
      //         time: 15.0,
      //         minimum: 200,
      //         maximum: 300,
      //       }),
      //     ],
      //     lifetime: 10.0, //发射粒子的时间
      //     modelMatrix: computeModelMatrix(ent, Cesium.JulianDate.now()),
      //     loop: false,
      //   })
      // );

      setTimeout(() => {
        // 爆炸完后清除
        viewer.scene.primitives.removeAndDestroy(particleSystem);
        // 同时清除粒子位置实体
        window.viewer.entities.removeById(ent.id);
        console.log("entities", window.viewer.entities);
        console.log("xxxx", viewer.scene.primitives);
      }, 3000);

      // 计算粒子特效模型位置矩阵
      function computeModelMatrix(entity, time) {
        var position = Cesium.Property.getValueOrUndefined(
          entity.position,
          time,
          new Cesium.Cartesian3()
        );
        if (!Cesium.defined(position)) {
          return undefined;
        }
        var orientation = Cesium.Property.getValueOrUndefined(
          entity.orientation,
          time,
          new Cesium.Quaternion()
        );
        if (!Cesium.defined(orientation)) {
          var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
            position,
            undefined,
            new Cesium.Matrix4()
          );
        } else {
          modelMatrix = Cesium.Matrix4.fromRotationTranslation(
            Cesium.Matrix3.fromQuaternion(orientation, new Cesium.Matrix3()),
            position,
            new Cesium.Matrix4()
          );
        }
        return modelMatrix;
      }
    },
    // 第二种加载gif图
    handleBoomGif() {
      this.loadGifByEntity(window.viewer, {
        image: "./symbol/boom6.gif",
        position: Cesium.Cartesian3.fromDegrees(120, 24),
      });
    },
    handleUnlock() {
      window.viewer.trackedEntity = null;
      this.$message.success("解锁成功");
    },
    loadGifByEntity(viewer, options) {
      console.log("billboard loadGif", options);
      const { image, position } = options;
      if (image) {
        const gifDiv = document.createElement("div");
        const gifImg = document.createElement("img");

        gifImg.setAttribute("rel:animated_src", image);
        gifImg.setAttribute("rel:auto_play", "1"); // 设置自动播放属性
        gifDiv.appendChild(gifImg);
        const superGif = new SuperGif({ gif: gifImg });
        superGif.load(function () {
          viewer.entities.add({
            position: position,
            billboard: {
              image: new Cesium.CallbackProperty(() => {
                return superGif.get_canvas().toDataURL("image/png");
              }, false),
              scale: 1,
              width: 100,
              height: 100,
            },
          });
        });
      }
    },
    handleDrawFanShape() {
      const fanDrawer = new DrawFanShape(window.viewer, "sectorDataSource", {
        color: Cesium.Color.BLUE, // 默认颜色
        labelFont: "16px Arial", // 标签字体
        labelFillColor: Cesium.Color.WHITE, // 标签颜色
      });
      const params = {
        id: "radar_001", // 扇形唯一标识
        position: Cesium.Cartesian3.fromDegrees(106.0, 26.0), // 中心点坐标（经度、纬度、高度）
        heading: Cesium.Math.toRadians(90), // 航向（弧度制，0为正北，顺时针增加）
        angle: 90, // 扇形角度（单位：度）
        radius: 5000, // 半径（单位：米）
        color: Cesium.Color.RED, // 扇形颜色及透明度
        label: "雷达覆盖区域", // 显示在扇形上的标签文字
        type: "radar", // 自定义分类（用于批量管理）
      };
      const sectorEntity = fanDrawer.drawSector(params);

      setTimeout(() => {
        fanDrawer.updateSector({
          id: "radar_001",
          color: new Cesium.Color.fromCssColorString("#008c8c"),
          radius: 1000,
          angle: 180,
        });
      }, 5000);

      // console.log("testSector", testSector);
    },
    handleDrawDragDiv() {
      // 使用
      const dataSource = new Cesium.CustomDataSource("label-datasource"); // 单独存储标牌的数据源
      function addDragLabelEntity() {
        const entity = new Cesium.Entity({
          id: `entity-id`,
          position: Cesium.Cartesian3.fromDegrees(123.0, 30.0, 1000),
          model: {
            show: true,
            uri: "./glb/zhanji.glb",
            scale: 1,
            minimumPixelSize: 128, // 模型的最小像素大小，而不考虑缩放
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              0.0,
              4e8
            ),
          },
        });
        window.viewer.entities.add(entity);
        dataSource.entities.add(entity);
        // 添加可拖拽标牌
        let table = new DragDiv(viewer, dataSource);
        table.addEntity(entity, {
          details: [
            { label: "名称：", value: "测试设备" },
            { label: "状态：", value: "完好" },
            { label: "经度：", value: "109.25560682" },
            { label: "纬度：", value: "34.63496935" },
            { label: "成功率：", value: "99%" },
          ],
        });
      }
      addDragLabelEntity();
    },
    handleTestRadar() {
      // 创建雷达半球
      // var radarDome = window.viewer.entities.add({
      //   position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 50),
      //   ellipsoid: {
      //     radii: new Cesium.Cartesian3(80, 80, 80),
      //     minimumClock: 0,
      //     maximumClock: Math.PI * 2,
      //     minimumCone: 0,
      //     maximumCone: Math.PI / 2,
      //     material: new Cesium.ColorMaterialProperty(
      //       Cesium.Color.GREEN.withAlpha(0.2)
      //     ),
      //     outline: true,
      //     outlineColor: Cesium.Color.GREEN,
      //   },
      // });
      // // 设置相机位置
      // viewer.camera.flyTo({
      //   destination: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 2000),
      //   orientation: {
      //     heading: Cesium.Math.toRadians(0),
      //     pitch: Cesium.Math.toRadians(-45),
      //     roll: 0.0,
      //   },
      // });
      // 使用示例：在经度-75.59777，纬度40.03883，高度50米处创建雷达
      // 半径100米，朝向45度，开合角60度
      const radar = this.createPartialRadar(
        -75.59777,
        40.03883,
        50,
        100,
        45,
        60
      );
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883, 2000),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-45),
          roll: 0.0,
        },
      });
      // viewer.camera.flyTo(radar);
    },
    createPartialRadar(longitude, latitude, height, radius, heading, aperture) {
      // 将朝向角从度转换为弧度
      heading = Cesium.Math.toRadians(heading);
      // 将开合角从度转换为弧度并除以2（因为要对称分布在朝向两侧）
      aperture = Cesium.Math.toRadians(aperture) / 2;

      // 计算最小和最大时钟角度（经度方向）
      const minClock = heading - aperture;
      const maxClock = heading + aperture;

      return window.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
        ellipsoid: {
          radii: new Cesium.Cartesian3(radius, radius, radius),
          innerRadii: new Cesium.Cartesian3(1, 1, 1),
          minimumClock: minClock,
          maximumClock: maxClock,
          minimumCone: 0, // 从顶部开始
          maximumCone: Math.PI / 2, // 只显示上半球
          material: new Cesium.ColorMaterialProperty(
            Cesium.Color.GREEN.withAlpha(0.3)
          ),
          outline: true,
          outlineColor: Cesium.Color.GREEN,
        },
      });
    },
    // 添加椭圆实体
    handleTestEllipse() {
      let ellipseEntity = viewer.entities.add({
        show: true,
        position: Cesium.Cartesian3.fromDegrees(
          123.99899399999983,
          35.662770000000044,
          6000
        ),
        ellipse: {
          semiMinorAxis: new Cesium.CallbackProperty(function () {
            // 根据相机距离计算大小
            const position = ellipseEntity.position.getValue(
              viewer.clock.currentTime
            );
            const cameraPosition = viewer.camera.position;
            const distance = Cesium.Cartesian3.distance(
              position,
              cameraPosition
            );

            // 基础大小(米) * 距离系数
            return (20 * distance) / 1000;
          }, false),
          semiMajorAxis: new Cesium.CallbackProperty(function () {
            // 同上，保持圆形可改为相同计算
            const position = ellipseEntity.position.getValue(
              viewer.clock.currentTime
            );
            const cameraPosition = viewer.camera.position;
            const distance = Cesium.Cartesian3.distance(
              position,
              cameraPosition
            );
            return (20 * distance) / 1000;
          }, false),
          material: new Cesium.ImageMaterialProperty({
            image: "./symbol/plane.png", // 图片以材质的方式填充
            color: Cesium.Color.RED.withAlpha(0.9),
            repeat: new Cesium.Cartesian2(1, 1),
          }),
          // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
          height: 6000, // 设置相对于地面的高度(米)

          // rotation: 45,
          // 利用下面这个属性设置素材填充时的选装角度（顺时针方向）
          stRotation: 0,
        },
      });
    },
    testRootState() {
      this.$store.dispatch("TestGetList");
    },
    // 添加范围雷达
    handleCamberRadar() {
      let position = Cesium.Cartesian3.fromDegrees(117.141, 31.95, 0);
      let modelMatrix = this.createModelMatrix(position, 0, 0, 0);
      let primitive = window.viewer.scene.primitives.add(
        new window.vis3d.sensor.CamberRadarPrimitive({
          modelMatrix: modelMatrix,
          color: Cesium.Color.fromCssColorString("#fff000").withAlpha(0.5),
          lineColor: Cesium.Color.fromCssColorString("#ffffff"),
          startRadius: 0, //内曲面半径
          radius: 5000 * 1000, //外曲面半径
          startFovH: Cesium.Math.toRadians(0), //左横截面角度，起始角度
          endFovH: Cesium.Math.toRadians(168), //右横截面角度，结束角度
          startFovV: Cesium.Math.toRadians(0), //垂直方向张角，起始角度
          endFovV: Cesium.Math.toRadians(90), //垂直方向张角，结束角度
          segmentH: 10, //Math.abs(item.endFovH - item.startFovH)/20,
          segmentV: 20,
          subSegmentH: 3,
          subSegmentV: 5,
          show: true,
        })
      );
      primitive.customName = "范围雷达";
    },
    // 创建模型矩阵
    createModelMatrix(position, heading, pitch, roll, scale, result) {
      scale = scale || 1;
      var enuMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        position,
        undefined,
        result
      );
      var scaleMatrix = Cesium.Matrix4.fromScale(
        new Cesium.Cartesian3(scale, scale, scale),
        new Cesium.Matrix4()
      );
      var modelMatrix = Cesium.Matrix4.multiply(
        enuMatrix,
        scaleMatrix,
        enuMatrix
      );
      var rotateMatrix = Cesium.Matrix3.fromHeadingPitchRoll(
        Cesium.HeadingPitchRoll.fromDegrees(heading, pitch, roll),
        new Cesium.Matrix3()
      );
      return Cesium.Matrix4.multiplyByMatrix3(
        modelMatrix,
        rotateMatrix,
        modelMatrix
      );
    },
  },
};
</script>

<style scoped lang="scss">
.map-container {
  width: 100vw;
  height: 100vh;
  background-color: #000;
  position: relative;
  display: flex;
  flex-direction: column;
  .map-content {
    flex: 1;
    overflow: hidden;
  }
  .map-header {
    height: 50px;
    background: #555;
    border-bottom: 1px solid #555;
    display: flex;
    align-items: center;
    padding: 0 16px;
    .map-header-right {
      margin-left: auto;
      color: #fff;
    }
  }
  .side-menu {
    position: absolute;
    z-index: 1;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0;
    margin: 0;
    li {
      width: 40px;
      height: 40px;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      text-align: center;
      line-height: 40px;
      cursor: pointer;
      &:hover {
        background-color: rgba(0, 0, 0, 0.8);
      }
    }
  }
  .simulation-control {
    position: absolute;
    right: 20px;
    width: 40px;
  }
}
</style>
